<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>目录浏览器</title>
  <script src="/assets/jquery.min.js"></script>
  <script src="/assets/tailwind.js"></script>
  <link href="/assets/font-awesome.min.css" rel="stylesheet">
  <link href="/assets/style.min.css" rel="stylesheet">
  <script src="/assets/jstree.min.js"></script>

  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3b82f6',
            secondary: '#64748b',
            neutral: '#f1f5f9',
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .scrollbar-hide {
        -ms-overflow-style: none;
        scrollbar-width: none;
      }
      .scrollbar-hide::-webkit-scrollbar {
        display: none;
      }
    }
  </style>
</head>

<body class="bg-gray-50 min-h-screen flex flex-col">
  <header class="bg-white shadow-sm sticky top-0 z-50">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-folder-open text-primary text-2xl"></i>
        <h1 class="text-xl font-semibold text-gray-800">目录浏览器</h1>
      </div>

      <div class="flex items-center space-x-4">
        <!-- 修改为设置为HTTP服务器目录按钮 -->
        <button id="set-http-dir-btn" class="p-2 rounded-full hover:bg-gray-100 transition-colors" title="设置为HTTP服务器目录">
          <i class="fa fa-server text-gray-600 mr-1"></i>设置为HTTP服务器目录
        </button>
        <button id="back-btn" class="p-1 rounded hover:bg-gray-100" title="返回" onclick="window.location.href = '/';">
          <i class="fa fa-home text-gray-600"></i>
        </button>
        <button id="refresh-btn" class="p-2 rounded-full hover:bg-gray-100 transition-colors" title="刷新">
          <i class="fa fa-refresh text-gray-600"></i>
        </button>
      </div>
    </div>
  </header>

  <!-- 新增：显示当前设置的HTTP服务器目录 -->
  <div class="bg-yellow-50 p-3 border-b border-yellow-200">
    <p id="http-server-dir-label" class="text-sm text-yellow-700 font-medium">
      <i class="fa fa-server text-yellow-600 mr-2"></i>当前HTTP服务器目录: 无
    </p>
  </div>

  <main class="flex-1 flex overflow-hidden">
    <aside class="w-64 bg-white border-r border-gray-200 overflow-y-auto scrollbar-hide transition-all duration-300"
      id="sidebar">
      <div class="p-4 border-b border-gray-200">
        <h2 class="font-medium text-gray-700">目录结构</h2>
      </div>
      <div id="directory-tree" class="p-2"></div>
    </aside>

    <div class="flex-1 flex flex-col bg-gray-50 overflow-hidden">
      <!-- 新增：显示当前目录路径的标签 -->
      <div class="bg-blue-50 p-3 border-b border-blue-200">
        <p id="current-path" class="text-sm text-blue-700 font-medium">
          <i class="fa fa-folder text-blue-600 mr-2"></i>当前目录: 根目录
        </p>
      </div>

      <div class="flex-1 overflow-y-auto p-4" id="directory-content">
        <div class="text-center text-gray-500 mt-16">
          <i class="fa fa-folder-open-o text-5xl mb-4"></i>
          <p>请从左侧选择一个目录</p>
        </div>
      </div>
    </div>
  </main>

  <script>
      let current_path = "";
      $(document).ready(function () {
        $('#http-server-dir-label').html(`
          <i class="fa fa-server text-yellow-600 mr-2"></i>当前HTTP服务器目录: {{ http_root }}
        `);
        // 初始化目录树
        $('#directory-tree').jstree({
          core: {
            data: {
              url: 'directories',
              data: function (node) {
                return { path: node.id };
              }
            },
            check_callback: true,
            themes: {
              responsive: false,
              stripes: true
            }
          },
          plugins: ['state', 'wholerow'], // 移除搜索插件
      });

      // 点击目录树节点
      $('#directory-tree').on('select_node.jstree', function (e, data) {
        const node = data.node;
        loadDirectoryContent(node.id);
        updateBreadcrumb(node);
        updateCurrentPath(node); // 更新当前路径标签
      });

      // 刷新按钮
      $('#refresh-btn').on('click', function () {
        $('#directory-tree').jstree('refresh');
      });

      // 设置为HTTP服务器目录按钮
      $('#set-http-dir-btn').on('click', async function () {
        const selectedNode = $('#directory-tree').jstree('get_selected')[0];
        if (selectedNode) {
          const pathString = getCurrentPath();
          $('#http-server-dir-label').html(`
            <i class="fa fa-server text-yellow-600 mr-2"></i>当前HTTP服务器目录: ${pathString}
          `);
           const result = await fetch('/saveroot', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    http_root_url: pathString,                   
                }),
            })
            .then(response => {
                console.log("response is ", response);
                if (!response.ok) {
                    return "根路径设置失败";
                }
                return "根路径设置成功";
            })
            .catch(error => {
                console.error('root directory add failed:', error);
                // Return empty results or handle error appropriately
                return [];
            }); 
        }
      });

      // 加载目录内容
      function loadDirectoryContent(path) {
        fetch(`directories/${encodeURIComponent(path)}`)
          .then(response => response.json())
          .then(data => {
            renderDirectoryContent(data);
          })
          .catch(error => {
            console.error('Error loading directory:', error);
            $('#directory-content').html(`
              <div class="text-center text-red-500 mt-16">
                <i class="fa fa-exclamation-triangle text-5xl mb-4"></i>
                <p>加载目录失败: ${error.message}</p>
              </div>
            `);
          });
      }

      // 渲染目录内容
      function renderDirectoryContent(data) {
        if (!data || !data.directories || data.directories.length === 0) {
          $('#directory-content').html(`
            <div class="text-center text-gray-500 mt-16">
              <i class="fa fa-folder-o text-5xl mb-4"></i>
              <p>此目录下没有子目录</p>
            </div>
          `);
          return;
        }

        let html = '<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">';

        data.directories.forEach(dir => {
          html += `
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow group cursor-pointer" data-path="${dir.path}">
              <div class="p-4 flex flex-col items-center justify-center">
                <div class="w-16 h-16 flex items-center justify-center mb-2 bg-blue-100 rounded-lg group-hover:bg-blue-200 transition-colors">
                  <i class="fa fa-folder text-blue-500 text-3xl"></i>
                </div>
                <div class="w-full text-center">
                  <p class="font-medium text-gray-800 truncate">${dir.name}</p>
                  <p class="text-xs text-gray-500 mt-1">修改于 ${formatDate(dir.modified)}</p>
                </div>
              </div>
            </div>
          `;
        });

        html += '</div>';
        $('#directory-content').html(html);

        // 绑定目录点击事件
        $('.cursor-pointer').on('click', function () {
          const path = $(this).data('path');
          const node = $('#directory-tree').jstree('get_node', path);

          if (node) {
            $('#directory-tree').jstree('select_node', node);
          } else {
            loadDirectoryContent(path);
            updateBreadcrumb({ id: path, text: path.split('/').pop() || path, parents: [] });
            updateCurrentPath({ id: path, text: path.split('/').pop() || path, parents: [] });
          }
        });
      }

      // 更新面包屑导航
      function updateBreadcrumb(node) {
        const $breadcrumb = $('#breadcrumb');
        $breadcrumb.empty();

        // 添加根目录
        $breadcrumb.append(`
          <span class="cursor-pointer hover:text-primary" data-path="">根目录</span>
          <i class="fa fa-angle-right text-gray-400 mx-1"></i>
        `);

        // 添加父目录
        const parents = [...node.parents].reverse();
        parents.forEach(parentId => {
          if (parentId === '#') return;

          const parentNode = $('#directory-tree').jstree('get_node', parentId);
          if (parentNode) {
            $breadcrumb.append(`
              <span class="cursor-pointer hover:text-primary" data-path="${parentId}">${parentNode.text}</span>
              <i class="fa fa-angle-right text-gray-400 mx-1"></i>
            `);
          }
        });

        // 添加当前目录
        $breadcrumb.append(`
          <span class="text-gray-900 font-medium">${node.text}</span>
        `);

        // 绑定面包屑点击事件
        $breadcrumb.find('[data-path]').on('click', function () {
          const path = $(this).data('path');
          const node = $('#directory-tree').jstree('get_node', path);

          if (node) {
            $('#directory-tree').jstree('select_node', node);
          } else if (path) {
            loadDirectoryContent(path);
            updateBreadcrumb({ id: path, text: path.split('/').pop() || path, parents: [] });
            updateCurrentPath({ id: path, text: path.split('/').pop() || path, parents: [] });
          } else {
            // 根目录
            $('#directory-tree').jstree('select_node', '#');
          }
        });
      }

      // 更新当前路径标签
      function updateCurrentPath(node) {
        const pathParts = [];
        const parents = [...node.parents].reverse();

        parents.forEach(parentId => {
          if (parentId !== '#') {
            const parentNode = $('#directory-tree').jstree('get_node', parentId);
            if (parentNode) {
              pathParts.push(parentNode.text);
            }
          }
        });

        pathParts.push(node.text);

        const pathString = pathParts.join(' / ') || '根目录';

        setCurrentPath(node.id);
        $('#current-path').html(`
          <i class="fa fa-folder text-blue-600 mr-2"></i>当前目录: ${node.id}
        `);
      }

      // 获取完整路径
      function getCurrentPath() {
        const pathParts = [];
        pathParts.push(current_path);
        return pathParts.join(' / ');
      }

      function setCurrentPath(str) {
        current_path = str;
      }

      // 格式化日期
      function formatDate(timestamp) {
        const date = new Date(timestamp * 1000); // 转换为毫秒
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN');
      }
    });
  </script>
</body>

</html>